package rcpexplorer.views;

import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.osgi.framework.Bundle;

public class OpenPluginXmlAction implements IObjectActionDelegate {

	private Bundle bundle;
	private IExtensionPoint extensionPoint;
	private IExtension extension;
	
	private BEPEBView view;

	public OpenPluginXmlAction() {
	}

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		this.view = null;
		if (targetPart instanceof BEPEBView) {
			this.view = (BEPEBView) targetPart;
		}
	}

	public void run(IAction action) {
		if (view == null) {
			return;
		}
		
		if (bundle != null){
			view.openPluginXml(bundle);
		} else if (extensionPoint != null) {
			view.openPluginXml(extensionPoint);			
		} else if (extension != null) {
			view.openPluginXml(extension);			
		}
	}

	public void selectionChanged(IAction action, ISelection selection) {
		bundle = null;
		extensionPoint = null;
		extension = null;
		action.setEnabled(false);
		if (selection instanceof ITreeSelection) {
			ITreeSelection treeSelection = (ITreeSelection) selection;
			TreePath[] paths = treeSelection.getPaths();
			if (paths.length > 0) {
				Object lastSegment = paths[0].getLastSegment();
				if (lastSegment instanceof Bundle) {
					bundle = ((Bundle) lastSegment);
					action.setEnabled(true);
				} else if (lastSegment instanceof AsBundleOf) {
					bundle = ((AsBundleOf) lastSegment).bundle;
					action.setEnabled(true);
				}  else if (lastSegment instanceof AsBundleDependency) {
					bundle = ((AsBundleDependency) lastSegment).bundle;
					action.setEnabled(true);
				} else if (lastSegment instanceof IExtensionPoint) {
					extensionPoint = (IExtensionPoint) lastSegment;
					action.setEnabled(true);					
				} else if (lastSegment instanceof AsExtensionPointIn) {
					extensionPoint = ((AsExtensionPointIn) lastSegment).extensionPoint;
					action.setEnabled(true);					
				} else if (lastSegment instanceof AsExtensionPointFor) {
					extensionPoint = ((AsExtensionPointFor) lastSegment).extensionPoint;
					action.setEnabled(true);					
				} else if (lastSegment instanceof IExtension) {
					extension = (IExtension) lastSegment;
					action.setEnabled(true);					
				} else if (lastSegment instanceof AsExtensionIn) {
					extension = ((AsExtensionIn) lastSegment).extension;
					action.setEnabled(true);					
				} else if (lastSegment instanceof AsExtensionOf) {
					extension = ((AsExtensionOf) lastSegment).extension;
					action.setEnabled(true);					
				}
			}
		}		
	}

}
